package com.wsapi.core.controller;

import com.wsapi.core.Module;
import com.wsapi.core.Module.ModulePermission;
import com.wsapi.core.Platform;
import com.wsapi.core.Platforms;
import com.wsapi.core.auth.UsernamePasswordCaptchaToken;
import com.wsapi.core.service.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理账号登录，注销登录相关请求
 */
@Controller
@RequestMapping("/identity")
public class IdentityController {

    @Resource
    private AccountService accountService;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "identity/login";
    }

    /**
     * 注销登陆
     *
     * @return
     */
    @RequestMapping("/quit")
    public String quit() {
        SecurityUtils.getSubject().logout();
        return "identity/login";
    }

    /**
     * 登录提交
     *
     * @param userName
     * @param password
     * @param captcha
     * @return
     */
    @RequestMapping("/enter")
    @ResponseBody
    public Map<String, Object> enter(String userName, String password,
            String captcha) {
        UsernamePasswordCaptchaToken token = new UsernamePasswordCaptchaToken(captcha, userName,
                password);
        Map<String, Object> result = new HashMap<>();
        Subject currentUser = SecurityUtils.getSubject();
        System.out.println(currentUser.isAuthenticated());
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            result.put("msg", "用户名不存在");
        } catch (IncorrectCredentialsException ice) {
            result.put("msg", "密码有误，请重试");
        } catch (LockedAccountException lae) {
            result.put("msg", "用户被锁，请联系管理员");
        } catch (ExcessiveAttemptsException eae) {
            result.put("msg", "超过最大尝试次数，请稍后再试");
        } catch (AuthenticationException ae) {
            result.put("msg", "发生内部错误，请重试");
        }
        if (currentUser.isAuthenticated()) {
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        return result;
    }

    /**
     * 根据当前登录用户的权限返回模块和权限
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/menu")
    public Map<String, Object> menu() {
        Map<String, Object> result = new HashMap<>();
        Subject currentUser = SecurityUtils.getSubject();
        List<Platform> allowPlatforms = new ArrayList<>();
        if (currentUser.isAuthenticated()) {
            List<Platform> platforms = Platforms.getPlatforms();
            for (Platform p : platforms) {
                List<Module> modules = p.getModules();
                Platform addP = null;
                for (Module m : modules) {
                    List<ModulePermission> permissionList = m
                            .getPermissionList();
                    Module addM = null;
                    for (ModulePermission mp : permissionList) {
                        if (currentUser.isPermitted(m.getId() + ":"
                                + mp.getKey())) {

                            if (addM == null) {
                                addM = new Module();
                                addM.setCode(m.getCode());
                                addM.setIconCls(m.getIconCls());
                                addM.setId(m.getId());
                                addM.setName(m.getName());
                                addM.setPermissionList(new ArrayList<ModulePermission>());
                            }
                            addM.getPermissionList().add(mp);
                        }
                    }
                    if (addM != null) {
                        if (addP == null) {
                            addP = new Platform();
                            addP.setCode(p.getCode());
                            addP.setIconCls(p.getIconCls());
                            addP.setId(p.getId());
                            addP.setName(p.getName());
                            addP.setModules(new ArrayList<Module>());
                        }

                        addP.getModules().add(addM);
                    }
                }
                if (addP != null) {
                    allowPlatforms.add(addP);
                }
            }
            result.put("planforms", allowPlatforms);
            result.put("success", true);
        } else {
            result.put("success", false);
        }
        return result;
    }
}
